//
//  StatusTableCellPictureView.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/6/1.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit
import SDWebImage

let pictureCellID = "homePictureCellReuseIdentifier"

class StatusTableCellPictureView: UICollectionView {

    var status : Status? {
    
        didSet{
            reloadData()
        }
    }
    
    /// 图片视图的layout
    private var pictureViewLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: pictureViewLayout)
        
        setupPictureView()
    }
    

    private func setupPictureView()
    {
        pictureViewLayout.minimumInteritemSpacing = 10
        pictureViewLayout.minimumLineSpacing = 10
        
        dataSource = self
        delegate = self
        
        registerClass(PictureViewCell.self, forCellWithReuseIdentifier: pictureCellID)
        backgroundColor = UIColor.whiteColor()
    }
    
    /**
     计算配图的尺寸
     */
    func calculateImageSize() -> CGSize
    {
        // 1.先取出图片的个数
        let count = status?.storedImageUrls?.count
        
        // 2.没有图片返回 CGSizeZero
        if count == nil || count == 0 {
            pictureViewLayout.itemSize = CGSize(width: 0.1, height: 0.1)
            return CGSize(width: 0.1, height: 0.1)
        }
        
        // 3.1张配图,计算尺寸
        if count == 1 {
            let key = status?.storedImageUrls?.first?.absoluteString
            let img = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            pictureViewLayout.itemSize = img.size
            return img.size
        }
        
        // 4.4张配图,按田字格布局计算
        let width = 90
        let margin = 10
        pictureViewLayout.itemSize = CGSize(width: width, height: width)
        
        if count == 4 {
            let imgWidth = width * 2 + margin
            return CGSize(width: imgWidth, height: imgWidth)
        }
        
        // 5.其他图片按九宫格布局
        let row = (count! - 1) / 3 + 1
        let column = 3
        let totalWidth = column * (width + margin) - margin
        let totalHeight = row * (width + margin) - margin
        return CGSize(width: totalWidth, height: totalHeight)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
/// 首页微博图片的点击通知
let WeiboStatusPictureTapNotification = "WeiboStatusPictureTapNotification"
/// 首页微博图片的索引的key
let WeiboStatusPictureIndexKey = "WeiboStatusPictureIndexKey"
/// 首页微博图片的url数组的key
let WeiboStatusPictureURLsKey = "WeiboStatusPictureURLsKey"

extension StatusTableCellPictureView : UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
    {
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return status?.storedImageUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureViewCell
        
        cell.imageURL = status?.storedImageUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
//        print(" selected + \(indexPath.item)")
//        print(status?.storedImageUrls![indexPath.item]);
        
        let infoDict = [WeiboStatusPictureIndexKey : indexPath,
                        WeiboStatusPictureURLsKey  : (status?.storedLargeImageUrls)!]
        
        NSNotificationCenter.defaultCenter().postNotificationName(WeiboStatusPictureTapNotification, object: self, userInfo: infoDict as [NSObject : AnyObject])
    }
}

private class PictureViewCell: UICollectionViewCell {
    
    
    var imageURL : NSURL? {
        
        didSet{
            imgView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initSubview()
    }
    
    private func initSubview()
    {
        contentView.addSubview(imgView)
        
        imgView.xmg_Fill(contentView)
    }
    
    // MARK:- 懒加载图片
    private lazy var imgView : UIImageView = UIImageView()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}